package thread;

import java.util.*;

/**
 * ArrayList，LinkedList和HashSet都不是并发安全的集合
 */
public class SyncDemo5 {
    public static void main(String[] args) {
        //Collections可以将一个现有的List集合转换为一个并发安全的List集合
        //Collection<Integer> c = new ArrayList<>();
        Collection<Integer> c = Collections.synchronizedList(new ArrayList<>());

        //Collection<Integer> c = new LinkedList<>();
        //Collection<Integer> c = Collections.synchronizedList(new LinkedList<>());

        //Collection<Integer> c = new HashSet<>();
        //Collection<Integer> c = Collections.synchronizedSet(new HashSet<>());


        Thread t1 = new Thread(()-> {
            for (int i = 0; i < 1000; i++) {
                c.add(i);
            }
        });

        Thread t2 = new Thread(()-> {
            for (int i = 0; i < 1000; i++) {
                c.add(i);
            }
        });

        t1.start();
        t2.start();

        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(c.size());
        System.out.println(c);
    }
}
